/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.order;

import com.lxk.oms.order.domain.bo.OmsOrderItemBo;
import com.lxk.service.core.Result;
import com.lxk.service.pms.api.PmsServiceApi;
import com.lxk.service.pms.request.ProductSkuUpdateStockParam;
import com.lxk.service.pms.response.SkuUpdateStockResult;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 预扣库存,支持普通订单
 *
 * @author heyi
 * 2024/8/21
 */
@LiteflowComponent(value = FlowOrderNodeConst.PRE_STOCK_REDUCE_ORDER)
@AllArgsConstructor
public class OrderPreStockNode extends NodeComponent {
    private final PmsServiceApi serviceApi;

    @Override
    public void process() throws Exception {
        OrderContext contextBean = getContextBean(OrderContext.class);
        ProductSkuUpdateStockParam param = new ProductSkuUpdateStockParam();
        List<OmsOrderItemBo> orderItemBoList = contextBean.getOrderItemBoList();
        List<ProductSkuUpdateStockParam.Item> itemList = orderItemBoList.stream().map(item -> {
            Long skuId = item.getSkuId();
            Integer count = item.getCount();
            return new ProductSkuUpdateStockParam.Item(skuId, count, "");
        }).collect(Collectors.toList());
        param.setItems(itemList);
        Result<SkuUpdateStockResult> preCutSkuStock = serviceApi.preCutSkuStock(param);
        if (preCutSkuStock.isFail()) {
            throw new ServiceException(preCutSkuStock.getMsg());
        }
        SkuUpdateStockResult result = preCutSkuStock.getData();
        // 如果预扣失败则提示
        if (!result.getResult()) {
            throw new ServiceException(result.getMessage());
        }
    }

    @Override
    public boolean isAccess() {
        OrderContext contextBean = getContextBean(OrderContext.class);
        return contextBean.getSaveDb() && contextBean.getNeedStock();
    }
}
